<?php

namespace app\admin\model\course;

use think\Model;
use traits\model\SoftDelete;

class UserCourse extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'user_course';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'study_status_text',
        'time_sum',//学习时长
        'section_count',//总章节
    ];

    public function getTimeSumAttr($value,$data)
    {
        $section_list = Section::all(['coursecontent_id' => $data['coursecontent_id']]);
        $study_time = 0;
        foreach ($section_list as $v){
            $data = UserSection::get(['section_id' => $v->id]);
            if($data){
                $study_time += $data->studytime;
            }
        }
        return $study_time;
    }

    public function getSectionCountAttr($value, $data)
    {
        $section_model = new Section();
        return $section_model->where(['coursecontent_id' => $data['coursecontent_id']])->count('id');
    }
    
    public function getStudyStatusList()
    {
        return ['0' => __('正在学习'), '1' => __('学习完成')];
    }


    public function getStudyStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['study_status']) ? $data['study_status'] : '');
        $list = $this->getStudyStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function coursecontent()
    {
        return $this->belongsTo('CourseContent', 'coursecontent_id', 'id', [], 'LEFT')->bind(['course_image' => 'image','course_name' => 'name']);
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->bind(['nickname','avatar','mobile']);
    }

}
